﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcShop.Models;
using System.Web.UI;
using System.IO;

namespace MvcShop.MVC.HtmlHelpers
{
    public class OnlinePollWriter
    {
        readonly IEnumerable<PollOption> _pollOp;
        readonly HtmlHelper _htmlHelper;
        readonly string _selectmode;

        public OnlinePollWriter(HtmlHelper htmlHelper, IEnumerable<PollOption> pollOp, string selectmode)
        {
            this._htmlHelper = htmlHelper;
            this._pollOp = pollOp;
            this._selectmode = selectmode;
        }

        public string Write()
        {
            var writer = new HtmlTextWriter(new StringWriter());
            writer.Write("<form id=\"pollForm\" action=\"/Home/HeadlePoll\" method=\"post\">");
            if (_pollOp != null)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                WriteOnlinePoll(writer, _pollOp);
                writer.RenderEndTag();
            } writer.Write("</from>");
            return writer.InnerWriter.ToString();
        }

         private void WriteOnlinePoll(HtmlTextWriter writer, IEnumerable<PollOption> pollOptions)
         {
             foreach (var po in pollOptions)
             {
                 writer.RenderBeginTag(HtmlTextWriterTag.Li);
                 if (_selectmode == "multipe")
                 {
                     writer.Write(WriteCheckBox(po));
                 }
                 else
                 {
                     writer.Write(WriteRadioButten(po));
                 } 
                 writer.RenderEndTag();
             }
             writer.RenderBeginTag(HtmlTextWriterTag.Li);
             writer.Write("<input type=\"submit\" value=\"提交\" />");
             writer.RenderEndTag();   
         }

         private string WriteRadioButten(PollOption po)
         {
             return "{0}{1}".With(_htmlHelper.RadioButton("PollOptionId", po.PollOptionId), po.Options);
         }

         private string WriteCheckBox(PollOption po)
         {
             return "<input type=\"checkbox\" name=\"PollOptionId\" value=\"{0}\" />{1}".With(po.PollOptionId, po.Options);
         }
    }
}
